package com.hongxun.design.activitys;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.adapters.CreateProjectAdapter;
import com.hongxun.design.bean.CodeSetVersionBean;
import com.hongxun.design.bean.CreateProjectBean;
import com.hongxun.design.bean.NewProjectBean;
import com.hongxun.design.bean.UserBean;
import com.hongxun.design.bean.photopassbean.SystemTypeBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.mytools.CheckClickTime;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.IntentToActivity;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.object_properties.MyMessage;
import com.hongxun.design.ui.dialogstyle.MyDialog;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.fileutil.GetFileUtil;
import com.hongxun.design.utils.fileutil.SetFileUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.httputil.PostParams;

import java.util.ArrayList;
import java.util.List;

import static com.hongxun.design.MyApp.activity;

/**
 * Created by zerdoor_pc on 2016/4/29.
 * 创建项目页
 */
public class CreateProjectActivity extends BaseActivity implements HeadSecond {
    private static String Tag = "CreateProjectActivity";
    ListView createproject_list;
    static CreateProjectAdapter madapter;
    Handler handler;
    List<CreateProjectBean> data;
    private final int SAVE = 0;
    private final int GETBACK = 1;
    private final int FINISH = 2;
    private final int SAVEPRO = 4;
    private AlertDialog dialog;
    private Handler proHandler;
    public String type;//界面类型创建与编辑
    public String stage_id = "0";
    public String project_id = "0";

    private void addCreateHandler() {
        proHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case SAVE://发送项目信息到服务器
                        proHandler.sendEmptyMessage(FINISH);
                        break;
                    case GETBACK:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            NewProjectBean bean = FastJsonUtil.JsonToGetId((String) msg.obj);
                            try {
                                MyApp.createProject.setProject_id(bean.project_id);
                                MyApp.createProject.setStage_id(bean.stage_id);
                                MyApp.createProject.setIs_exp(MString.code_zero);
                                MyApp.createProject.setCurrent_schedule("11");
                                MyApp.createProject.setCreate_time((System.currentTimeMillis() / 1000) + "");
                                MyApp.currProject.setBean(MyApp.createProject);
                                MyApp.createProject.clearBean();
                            } catch (Exception e) {
                                MyApp.createProject.clearBean();
                            }
                            MyApp.iscreate = true;
                            PostParams.map.put(MString.flag, MString.add);
                            SetFileUtil.createProjectStageListFile(JSON.toJSONString(PostParams.map));
                            //保存项目基本信息
                            PostParams.map.put(MString.manager, MyApp.currProject.getManager_name());
                            PostParams.map.put(MString.manager_id, MyApp.currProject.getManager());
                            PostParams.map.put(MString.explorationer, MyApp.currProject.getExplorationer_name());
                            PostParams.map.put(MString.explorationer_id, MyApp.currProject.getExplorationer());
                            SetFileUtil.setProjectInfo(JSON.toJSONString(PostParams.map));
                            PostParams.map.put(MString.explorationer, MyApp.currProject.getExplorationer());
                            PostParams.map.put(MString.manager, MyApp.currProject.getManager());
                            SetFileUtil.SaveFileRequestData(JSON.toJSONString(PostParams.map));

                            ToastShow.showShort(mActivity, "操作成功!");
                            MyApp.iscreate = true;
                            dialog = MyDialog.dialogForCreatePro(CreateProjectActivity.this, proHandler, SAVE);
                        } else {
                            ToastShow.showShort(mActivity, "操作失败," + s);
                        }
                        break;
                    case FINISH://开始踏勘
                        IntentToActivity.intent(mActivity, ReconnaissanceActivity.class);
                        dialog.dismiss();
                        finish();
                        break;
                    case SAVEPRO:
                        CreateProjectBean bean = madapter.getData().get(madapter.mPosition);
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            String path = FastJsonUtil.JsonToPath((String) msg.obj);
                            bean.setPath(path);
                        } else {
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj) + ",语音上传失败！");
                            bean.setPath("");
                        }
                        save();
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, "系统异常,保存失败！");
                        //dialog = MyDialog.dialogForCreatePro(CreateProjectActivity.this, proHandler, SAVE);
                        break;

                    default:
                        break;
                }
            }
        };
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_createproject);
        addCreateHandler();
        findBar();
        findView();
        initialization();
    }

    @Override
    protected void onStart() {
        activity = this;
        super.onStart();
    }

    @SuppressLint("NewApi")
    @Override
    public void findBar() {
        try {
            Bundle bundle = getIntent().getExtras();
            type = bundle.getString(MString.TYPE, "");
        } catch (Exception e) {
            type = "";
        }

        String title = MString.CreateProject;
        if (type.equals(MString.ISEDIT)) {
            title = MyApp.currProject.getProject_name();
            stage_id = MyApp.currProject.getStage_id();
            project_id = MyApp.currProject.getProject_id();
        }
        HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.headsecond_layout);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean((String) IconSourse.FORGETPASSWORD,
                View.INVISIBLE, R.color.bar_right, ListenerSet.back, title, R.color.title, View.VISIBLE,
                IconSourse.BACK + "", View.VISIBLE));
    }

    @Override
    protected void findView() {
        createproject_list = (ListView) findViewById(R.id.createproject_list);
        TextView preservation = (TextView) findViewById(R.id.preservation);
        SetTypeface.set(preservation, IconSourse.SURE);
        super.findView();
    }


    @Override
    protected void initialization() {
        data = DataUtil.getJGCreateItemData();
        madapter = new CreateProjectAdapter(data, this);
        createproject_list.setAdapter(madapter);

        if (type.equals(MString.ISEDIT)) {
            AddBaseHandler();
            addUpProjectHandler();
            getBaseData();
        }
        super.initialization();
    }

    /**
     * ********************************项目基础信息************************************************
     */
    private Handler baseHandler;
    private Handler upProjectHandler;

    /**
     * 获取项目信息*
     */
    private void getBaseData() {
        if (MyApp.isOnLine) {
            MyApp.HTTP.getProjectInfo(baseHandler, HttpStringUtil.SUCCESSED, stage_id);
        } else {
            baseHandler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED, GetFileUtil.getProjectInfo()));
        }
    }

    /**
     * 获取项目信息Handler*
     */
    private void AddBaseHandler() {
        baseHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (MyApp.isOnLine) {
                                SetFileUtil.setProjectInfo((String) msg.obj);
                            }
                            if (JSON.parseObject((String) msg.obj).size() > 0) {
                                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject((String) msg.obj);
                                if (data != null) {
                                    data.clear();
                                    data.addAll(DataUtil.getJGCreateItemData());
                                } else {
                                    data = DataUtil.getJGCreateItemData();
                                }
                                for (CreateProjectBean b : data) {
                                    if (jsonObject.containsKey(b.getSendCode())) {
                                        switch (b.getItemType()) {
                                            case Constant.CREATE_GENERAL:
                                                switch (b.getIsWrite()) {
                                                    case Constant.CLICKEDTEXT:
                                                        b.setValue(jsonObject.getString(b.getSendCode()));
                                                        break;
                                                    case Constant.CLICKPOP:
                                                        b.setValuecode(jsonObject.getString(b.getSendCode()));
                                                        for (SystemTypeBean s : b.getList()) {
                                                            if (s.getTypecode().equals(jsonObject.getString(b.getSendCode()))) {
                                                                b.setValue(s.getTypename());
                                                                break;
                                                            }
                                                        }
                                                        break;
                                                    case Constant.CLICKACTIVITY:
                                                        if (b.getSendCode().equals(MString.address)) {
                                                            b.setValue(jsonObject.getString(b.getSendCode()));
                                                            if (jsonObject.getDouble(MString.alt) != null) {
                                                                b.setLating(new double[]{jsonObject.getDouble(MString.lng), jsonObject.getDouble(MString.lat), jsonObject.getDouble(MString.alt)});
                                                            } else {
                                                                b.setLating(new double[]{jsonObject.getDouble(MString.lng), jsonObject.getDouble(MString.lat)});
                                                            }
                                                        } else if (b.getSendCode().equals(MString.manager)
                                                                || b.getSendCode().equals(MString.explorationer)) {
                                                            String names = jsonObject.getString(b.getSendCode());
                                                            String code = MString.explorationer_id;
                                                            if (b.getSendCode().equals(MString.manager))
                                                                code = MString.manager_id;
                                                            String ids = jsonObject.getString(code);
                                                            b.setValue(names);
                                                            b.setValuecode(ids);
                                                            b.setExplorationer_id(jsonObject.getString(code));

                                                            String[] tar = names.split(",");
                                                            String[] idtar = ids.split(",");
                                                            List<UserBean> beans = new ArrayList<>();
                                                            for (int i = 0; i < tar.length; i++) {
                                                                UserBean bean = new UserBean();
                                                                bean.setId(idtar[i]);
                                                                bean.setRealname(tar[i]);
                                                                bean.setUsername(tar[i]);
                                                                beans.add(bean);
                                                            }
                                                            b.setObj(beans);
                                                        } else {
                                                            b.setValue(jsonObject.getString(b.getSendCode()));
                                                        }
                                                        break;
                                                }
                                                break;
                                            case Constant.CREATE_REMARKS:
                                                b.setValue(jsonObject.getString(b.getSendCode()));
                                                break;
                                        }
                                    }
                                }
                                baseHandler.sendEmptyMessage(1);
                            }
                        } else {
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case 1:
                        if (madapter == null) {
                            madapter = new CreateProjectAdapter(data, mActivity);
                            createproject_list.setAdapter(madapter);
                        } else {
                            madapter.notifyDataSetChanged();
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                }
            }
        };
    }

    /**
     * 保存信息回调*
     */
    private void addUpProjectHandler() {
        upProjectHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            MyApp.currProject.setBean(MyApp.createProject);
                            MyLog.L("上传文件：刷新接束 " + JSON.toJSONString(MyApp.currProject));
                            ToastShow.showShort(mActivity, "修改成功！");
                            mActivity.onBackPressed();
                        } else {
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                }
            }
        };
    }

    /**
     * 保存方法*
     */

    public void preserVation(View v) {
        if (CheckClickTime.back(this)) {
            showWaitDialog(-1, "处理中...");
            boolean flag = true, bool1 = false, bool2 = false;
            String note = "创建人必须是负责人和参与人!";
            for (CreateProjectBean bean : data) {
                if (bean.ismustInput() && TextUtils.isEmpty(bean.getValue().trim())) {
                    note = "必填项不能为空";
                    flag = false;
                    break;
                }
                if (bean.getSendCode().equalsIgnoreCase(MString.address)) {
                    if (bean.getLating() == null || bean.getLating()[0] == 4.9E-324
                            || bean.getLating()[1] == 4.9E-324) {
                        note = "定位失败";
                        flag = false;
                        break;
                    }
                }
                if (bean.getTypeName().equals(Constant.项目团队人员)) {
                    String valuecode = bean.getValuecode();
                    if (TextUtils.isEmpty(valuecode)) {
                        valuecode = MyApp.userInfo.getUser_id();
                        bean.setValuecode(valuecode);
                        bean.setValue(MyApp.userInfo.getRealname());
                    }
                    if (bean.getSendCode().equalsIgnoreCase(MString.manager)) {
                        if (valuecode.contains(MyApp.userInfo.getUser_id())
                                && bean.getValue().contains(MyApp.userInfo.getRealname())) {
                            bool1 = true;
                        }
                    } else if (bean.getSendCode().equalsIgnoreCase(MString.explorationer)) {
                        if (valuecode.contains(MyApp.userInfo.getUser_id())
                                && bean.getValue().contains(MyApp.userInfo.getRealname())) {
                            bool2 = true;
                        }
                    }
                }
            }
            if (!bool1 || !bool2) flag = false;

            if (!flag) {
                hideWaitIngDialog();
                ToastShow.showShort(this, note);
                return;
            } else {
                save();
            }
        }
    }


    private void save() {
        hideWaitIngDialog();
        saveUserInfo();
        if (type.equals(MString.ISEDIT)) {
            if (MyApp.isOnLine) {
                MyApp.HTTP.UpProject(upProjectHandler, HttpStringUtil.SUCCESSED, data, stage_id);
            } else {
                MyApp.createProject.setBean(MyApp.currProject);
                PostParams.CreateProject(data);
                PostParams.map.put(MString.stage_id, stage_id);
                PostParams.map.put(MString.project_id, project_id);
                MyApp.currProject.setBean(MyApp.createProject);
                MyApp.currProject.setProject_id(project_id);
                CreateProjectBean bean = null;
                if (madapter.mPosition != -1) bean = madapter.getData().get(madapter.mPosition);
                //离线时移动录音到缓存
                String path = "";
                if (bean != null && madapter.mPosition != -1 && bean.getPath() != null && bean.getPath().length() > 0 && !bean.getPath().contains(MyApp.File.getCachaProVoicePath())) {
                    path = MyApp.File.getCachaProVoicePath() + "voice.amr";
                    String path1 = MyApp.File.getCachaProVoiceRequestPath() + "voice.amr";
                    MyApp.File.copyFile(bean.getPath(), path);
                    MyApp.File.copyFile(bean.getPath(), path1);
                    bean.setPath(path);
                }
                if (MyApp.currProject.getProject_id().equals(MString.code_null) || MyApp.currProject.getProject_id().equals(MString.code_zero) || stage_id.equals(MString.code_null) || stage_id.equals(MString.code_zero)) {
                    PostParams.map.put(MString.flag, MString.add);
                } else {
                    PostParams.map.put(MString.flag, MString.up);
                }
                SetFileUtil.updateProjectStageListFile();
                PostParams.map.put(MString.manager, MyApp.currProject.getManager_name());
                PostParams.map.put(MString.manager_id, MyApp.currProject.getManager());
                PostParams.map.put(MString.explorationer, MyApp.currProject.getExplorationer_name());
                PostParams.map.put(MString.explorationer_id, MyApp.currProject.getExplorationer());
                SetFileUtil.setProjectInfo(JSON.toJSONString(PostParams.map));
                if (path.length() == 0) {
                    PostParams.map.put(MString.voice_remark, "");
                } else {
                    PostParams.map.put(MString.voice_remark, "voice.amr");
                }
                /**"power_zone": "11",
                 "stage": "14",
                 "weather_zone": "11",
                 "current_stage": "14",
                 designer
                 auditor
                 */
                PostParams.map.put(MString.power_zone, "11");
                PostParams.map.put(MString.stage, "14");
                PostParams.map.put(MString.weather_zone, "11");
                PostParams.map.put(MString.current_stage, "14");
                PostParams.map.put(MString.designer, MyApp.currProject.getManager());
                PostParams.map.put(MString.auditor, MyApp.currProject.getManager());

//                PostParams.map.put(MString.designer, MyApp.currProject.getManager());
//                PostParams.map.put(MString.auditor, MyApp.currProject.getManager());

                PostParams.map.put(MString.manager, MyApp.currProject.getManager());
                PostParams.map.put(MString.explorationer, MyApp.currProject.getExplorationer());
                SetFileUtil.SaveFileRequestData(JSON.toJSONString(PostParams.map));
                ToastShow.showShort(mActivity, "修改成功！");
                mActivity.onBackPressed();
            }
        } else {
            if (MyApp.isOnLine) {
                MyApp.HTTP.sendProject(proHandler, GETBACK, data);
            } else {
                String path = "";
                MyApp.createProject.setProject_id("");
                MyApp.createProject.setStage_id("");
                MyApp.createProject.setUUID(MString.getMyUUID());
                MyApp.createProject.setIs_exp(MString.code_zero);
                MyApp.createProject.setCurrent_schedule("11");
                MyApp.createProject.setCreate_time((System.currentTimeMillis() / 1000) + "");
                PostParams.CreateProject(data);
                MyApp.currProject.setBean(MyApp.createProject);
//                    PostParams.map.put(MString.stage_id, MyApp.currProject.getStage_id());
                PostParams.map.put(MString.uuid, MyApp.currProject.getUUID());
                CreateProjectBean bean = null;
                if (madapter.mPosition != -1) bean = madapter.getData().get(madapter.mPosition);
                //离线时移动录音到缓存
                if (bean != null && madapter.mPosition != -1 && bean.getPath() != null && bean.getPath().length() > 0 && !bean.getPath().contains(MyApp.File.getCachaProVoicePath())) {
                    path = MyApp.File.getCachaProVoicePath() + "voice.amr";
                    String path1 = MyApp.File.getCachaProVoiceRequestPath() + "voice.amr";
                    MyApp.File.copyFile(bean.getPath(), path);
                    MyApp.File.copyFile(bean.getPath(), path1);
                    PostParams.map.put(MString.voice_remark, path);
                    bean.setPath(path);
                }
                MyApp.createProject.clearBean();
                ToastShow.showShort(mActivity, "创建成功!");
                MyApp.iscreate = true;
                PostParams.map.put(MString.flag, MString.add);
                SetFileUtil.createProjectStageListFile(JSON.toJSONString(PostParams.map));
                /**保存项目基本信息**/
                PostParams.map.put(MString.manager, MyApp.currProject.getManager_name());
                PostParams.map.put(MString.manager_id, MyApp.currProject.getManager());
                PostParams.map.put(MString.explorationer, MyApp.currProject.getExplorationer_name());
                PostParams.map.put(MString.explorationer_id, MyApp.currProject.getExplorationer());
                SetFileUtil.setProjectInfo(JSON.toJSONString(PostParams.map));
                if (path.length() == 0) {
                    PostParams.map.put(MString.voice_remark, "");
                } else {
                    PostParams.map.put(MString.voice_remark, "voice.amr");
                }
                /**"power_zone": "11",
                 "stage": "14",
                 "weather_zone": "11",
                 "current_stage": "14",
                 designer
                 auditor
                 */
                PostParams.map.put(MString.power_zone, "11");
                PostParams.map.put(MString.stage, "14");
                PostParams.map.put(MString.weather_zone, "11");
                PostParams.map.put(MString.current_stage, "14");
                PostParams.map.put(MString.designer, MyApp.currProject.getManager());
                PostParams.map.put(MString.auditor, MyApp.currProject.getManager());

                PostParams.map.put(MString.explorationer, MyApp.currProject.getExplorationer());
                PostParams.map.put(MString.manager, MyApp.currProject.getManager());
                SetFileUtil.SaveFileRequestData(JSON.toJSONString(PostParams.map));
                dialog = MyDialog.dialogForCreatePro(CreateProjectActivity.this, proHandler, SAVE);
            }
        }
    }

    //新增项目时：保存选择后的人员信息到本地
    private void saveUserInfo() {
        String toJson;
        if (userBeen0 != null) {
            toJson = "{\"11\":" + FastJsonUtil.beanToJson(userBeen0) + "}";
            ShardPreferencesTool.saveshare(MyApp.activity, MString.UserByTypeList + 11, toJson);
        }
        if (userBeen1 != null) {
            toJson = "{\"12\":" + FastJsonUtil.beanToJson(userBeen1) + "}";
            ShardPreferencesTool.saveshare(MyApp.activity, MString.UserByTypeList + 12, toJson);
        }
    }


    public static View view;
    private static List<UserBean> userBeen0, userBeen1;

    //设置返回数据
    public static void setValue(String type, Object value, String TYPENUM, String... name) {
        int position = Integer.parseInt(TYPENUM);
        if (position == -1) return;
        switch (type) {
            case Constant.ACTIVITYCODESET:
                madapter.getData().get(position).setCodeSetVersion((CodeSetVersionBean) value);
                madapter.getData().get(position).setValue(name[0] + ((CodeSetVersionBean) value).codeset_version);
                break;
            case Constant.ACTIVITYMULTISELECT:
                //为了离线操作顺利
                if (madapter.getData().get(position).getSendCode().equalsIgnoreCase(MString.manager)) {
                    userBeen0 = (List<UserBean>) value;
                } else if (madapter.getData().get(position).getSendCode().equalsIgnoreCase(MString.explorationer)) {
                    userBeen1 = (List<UserBean>) value;
                }
                madapter.getData().get(position).setObj(value);
                madapter.getData().get(position).setValue(getName((List<UserBean>) value));
                madapter.getData().get(position).setValuecode(getCode((List<UserBean>) value));
                break;
        }
        madapter.notifyDataSetChanged();
    }

    private static String getName(List<UserBean> beans) {
        if (beans == null || beans.size() == 0) return "";
        String s = "";
        for (UserBean bean : beans) {
            s += bean.getRealname() + ",";
        }

        return s.substring(0, s.length() - 1);
    }

    private static String getCode(List<UserBean> beans) {
        if (beans == null || beans.size() == 0) return "";
        String s = "";
        for (UserBean bean : beans) {
            s += bean.getId() + ",";
        }
        return s.substring(0, s.length() - 1);
    }

    //设置地图返回数据
    public static void setValue(String type, String value, double[] lating) {
        int position = -1;
        if (madapter.map == null) return;
        position = madapter.map.get(type);
        if (position == -1) return;
        madapter.getData().get(position).setValue(value);
        if (lating != null) {
            madapter.getData().get(position).setLating(lating);
        }
        madapter.notifyDataSetChanged();
    }

    //设置土质/运输返回数据
    public static void setValue(String type, String[] value) {
        MyLog.L(MyApp.AppName + Tag + "type：" + type + "  value:" + value);
        int position = -1;
        if (madapter.map == null) return;
        position = madapter.map.get(type);
        if (position == -1) return;
        madapter.getData().get(position).setValuearr(value);
        madapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        madapter = null;
        data = null;
        userBeen0 = null;
        userBeen1 = null;
        super.onDestroy();
    }
}
